<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Organization;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('permission:view-users')->only(['index', 'show']);
        $this->middleware('permission:create-users')->only(['create', 'store']);
        $this->middleware('permission:edit-users')->only(['edit', 'update']);
        $this->middleware('permission:delete-users')->only(['destroy']);
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $users = User::with(['roles', 'organizations'])->paginate(10);
        return view('admin.users.index', compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $roles = Role::all();
        $organizations = Organization::where('is_active', true)->orderBy('name')->get();
        return view('admin.users.create', compact('roles', 'organizations'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'roles' => 'array',
            'organizations' => 'array',
            'admin_organizations' => 'array',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        if ($request->roles) {
            $user->assignRole($request->roles);
        }
        
        // 处理组织关联
        $organizationData = [];
        
        // 添加普通成员关系
        if ($request->organizations) {
            foreach ($request->organizations as $orgId) {
                $organizationData[$orgId] = ['is_admin' => false];
            }
        }
        
        // 添加管理员关系
        if ($request->admin_organizations) {
            foreach ($request->admin_organizations as $orgId) {
                $organizationData[$orgId] = ['is_admin' => true];
            }
        }
        
        if (!empty($organizationData)) {
            $user->organizations()->attach($organizationData);
        }

        return redirect()->route('admin.users.index')->with('success', '用户创建成功！');
    }

    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        $user->load('roles', 'permissions', 'organizations', 'managedOrganizations');
        return view('admin.users.show', compact('user'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(User $user)
    {
        $roles = Role::all();
        $organizations = Organization::where('is_active', true)->orderBy('name')->get();
        $user->load('organizations');
        return view('admin.users.edit', compact('user', 'roles', 'organizations'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, User $user)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
            'password' => 'nullable|string|min:8|confirmed',
            'roles' => 'array',
            'organizations' => 'array',
            'admin_organizations' => 'array',
        ]);

        $user->update([
            'name' => $request->name,
            'email' => $request->email,
        ]);

        if ($request->password) {
            $user->update(['password' => Hash::make($request->password)]);
        }

        $user->syncRoles($request->roles ?? []);
        
        // 处理组织关联
        $organizationData = [];
        
        // 添加普通成员关系
        if ($request->organizations) {
            foreach ($request->organizations as $orgId) {
                $organizationData[$orgId] = ['is_admin' => false];
            }
        }
        
        // 添加管理员关系
        if ($request->admin_organizations) {
            foreach ($request->admin_organizations as $orgId) {
                $organizationData[$orgId] = ['is_admin' => true];
            }
        }
        
        // 同步组织关系
        $user->organizations()->sync($organizationData);

        return redirect()->route('admin.users.index')->with('success', '用户更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(User $user)
    {
        $user->delete();
        return redirect()->route('admin.users.index')->with('success', '用户删除成功！');
    }
}
